package com.lujieni.threadpool.util;

import lombok.Data;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;

@Data
public class CompareUtil<T> {

    private List<Function<T, ?>> fieldList;

    public CompareUtil(){
        this.fieldList = new ArrayList<>();
    }

    public CompareUtil<T> addField(Function<T, ?> field){
        fieldList.add(field);
        return this;
    }

    // 静态方法不能直接使用类上的泛型 只能自己声明
    public static <T> boolean startCompare(T a, T b, CompareUtil<T> compareUtil){
        for (Function<T, ?> function : compareUtil.getFieldList()) {
            int i = doCompare(function.apply(a), function.apply(b));
            if(i != 0){
                return false;
            }
        }
        return true;
    }

    private static int doCompare(Object a, Object b){
        if(a == null && b == null){
            return 0;
        }
        if(a == null){
            return 1;
        }
        if(b == null){
            return -1;
        }
        if(a instanceof String){
            return ((String) a).compareTo( (String) b );
        }
        if(a instanceof Integer){
            return ((Integer) a).compareTo( (Integer) b );
        }
        if(a instanceof BigDecimal){
            return ((BigDecimal) a).compareTo( (BigDecimal) b );
        }
        return 0;
    }

}
